package com.spider.site.web.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.spider.site.entity.User;

/**
 * 拦截器
 * 
 * @author wq
 *
 */
@Configuration
public class LoginHandler implements WebMvcConfigurer {

	private UserInterceptor userInterceptor = null;

	public LoginHandler() {
		if (this.userInterceptor == null) {
			this.userInterceptor = new UserInterceptor();
		}
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(this.userInterceptor).addPathPatterns("/**")//拦截所有
				.excludePathPatterns("/")
		 		.excludePathPatterns("/spiderToLogin")
				.excludePathPatterns("/spiderLogin")
				.excludePathPatterns("/index")
				.excludePathPatterns("/boostrap4/**")
				.excludePathPatterns("/js/**")
				.excludePathPatterns("/images/**");
	}

	/**
	 * 内部类
	 * 
	 * @author wq
	 */
	class UserInterceptor implements HandlerInterceptor {

		@Override
		public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
				Exception ex) throws Exception {
			HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
		}

		@Override
		public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
				ModelAndView modelAndView) throws Exception {
			HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
		}

		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
				throws Exception {
			User user = (User) request.getSession().getAttribute("spiderUser");
			if (user == null) {
				response.sendRedirect("/spiderToLogin");
				return false;
			}
			return true;
		}

	}

}
